var timer = require('../../utils/timer.js')

Page({
  data: {
    voiceFile: [],
    state: 0, // 初始化
    voiceFile: [],
    icon_shape: 'circle', // square /circle

  },
  recorderManager: null,
  audioCtx: null,

  onLoad() {
    this.getStoreFilesList()

  },
  onReady() {
    this.recorderManager = wx.getRecorderManager()
    this.audioCtx = wx.createInnerAudioContext()

    this.audioCtx.onPlay(() => {
      console.log('开始播放')
    })
    this.audioCtx.onEnded(()=>{
      // onEnded自然结束，onStop()手动结束
      console.log('播放结束')
      this.setData({
        voiceid: 'no'
      })
    })
    this.audioCtx.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    this.recorderManager.onStop((res) => {
      console.log('')
      console.log('stop', res, res.tempFilePath)
      // 当录音结束后，将临时文件存入store文件夹中
      this.saveTmpFile(res.tempFilePath)
    })
  },

  click() {
    var state = this.data.state
    if (state) {
      this.stop()
    } else {
      this.start()
    }

    var state = state == 1 ? 0 : 1
    var icon_shape = this.data.icon_shape == 'circle' ? 'square' : 'circle'
    this.setData({
      state,
      icon_shape
    })
  },
  /**
   * 开始录音
   */
  start() {
    // 停止音频播放
    this.audioCtx.stop()
    // 恢复正在播放状态
    this.setData({
      voiceid: 'no'
    })
    timer.onTimeUpdate(time => {
      this.setData({ time })
    })
    timer.start()
    this.recorderManager.start({
      format: 'mp3' // 保存格式为mp3，默认是acc
    })
  },

  /**
   * 停止录音
   */
  stop() {
    timer.reset()
    this.recorderManager.stop()
  },
  /**
   * tmp文件夹的文件保存到store文件夹
   * @param {String} tmpFilePath 临时文件夹路径
   */
  saveTmpFile(tmpFilePath) {
    var that = this
    var FileSystemManager = wx.getFileSystemManager()
    FileSystemManager.saveFile({
      tempFilePath: tmpFilePath, // 临时文件夹路径
      success(res) {
        console.log('saveTmpFile', res)
        that.getStoreFilesList() // 保存成功后获取一次store文件夹文件列表
      }
    })
  },

  /**
   * 获取store文件夹内所有文件信息
   */
  getStoreFilesList() {
    var fs = wx.getFileSystemManager()
    var _this = this
    fs.getSavedFileList({
      success(res) {
        console.log('getStoreFileslist', res.fileList)
        _this.setData({
          voiceFile: res.fileList
        })
      }
    })
  },
  play(e) {
    timer.reset()
    var voiceid = e.currentTarget.dataset.voiceid
    this.setData({
      voiceid
    })
    this.audioCtx.src = this.data.voiceFile[voiceid].filePath
    this.audioCtx.play()
    console.log('play:', this.data.voiceFile[voiceid].filePath)
  }
})